package com.qingyunge.app.dws;

import com.alibaba.fastjson.JSONObject;
import com.qingyunge.bean.HaoPingAvgBean;
import com.qingyunge.bean.HaoPingAvgRes;
import com.qingyunge.util.MyClickHouseUtil;
import com.qingyunge.util.MyKafkaUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.util.Collector;

import java.time.Duration;

public class Dws_haoping_avg_pro_view_window {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment().setParallelism(1);
        String topic = "dwd_traffic_sku";
        String gourpid = "Dws_haoping_avg_pro_view";
        SingleOutputStreamOperator<HaoPingAvgBean> haoPingDS = env.addSource(MyKafkaUtil.getFlinkKafkaConsumer(topic, gourpid))
                .flatMap(new FlatMapFunction<String, HaoPingAvgBean>() {
                    @Override
                    public void flatMap(String s, Collector<HaoPingAvgBean> collector) throws Exception {
                        try {
                            JSONObject jsonObject = JSONObject.parseObject(s);
                            Long ts = jsonObject.getLong("ts");
                            JSONObject data = jsonObject.getJSONObject("data");
                            String skuClass = data.getString("id").substring(0, 1);
                            Long por_view = data.getLong("por_view");
                            HaoPingAvgBean haoPingAvgBean = new HaoPingAvgBean(skuClass, por_view, 1L, ts);
                            collector.collect(haoPingAvgBean);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
        SingleOutputStreamOperator<HaoPingAvgBean> haopingWaterMark = haoPingDS.assignTimestampsAndWatermarks(WatermarkStrategy.<HaoPingAvgBean>forBoundedOutOfOrderness(Duration.ofSeconds(2)).withTimestampAssigner(new SerializableTimestampAssigner<HaoPingAvgBean>() {
            @Override
            public long extractTimestamp(HaoPingAvgBean haoPingAvgBean, long l) {
                return haoPingAvgBean.getTs();
            }
        }));
        SingleOutputStreamOperator<HaoPingAvgBean> reduceDS = haopingWaterMark.keyBy(new KeySelector<HaoPingAvgBean, String>() {
            @Override
            public String getKey(HaoPingAvgBean haoPingAvgBean) throws Exception {
                return haoPingAvgBean.getSkuClass();
            }
        }).window(TumblingEventTimeWindows.of(Time.seconds(10)))
                .reduce(new ReduceFunction<HaoPingAvgBean>() {
                    @Override
                    public HaoPingAvgBean reduce(HaoPingAvgBean haoPingAvgBean, HaoPingAvgBean t1) throws Exception {
                        haoPingAvgBean.setPor_view(haoPingAvgBean.getPor_view() + t1.getPor_view());
                        haoPingAvgBean.setCount(haoPingAvgBean.getCount() + t1.getCount());
                        return haoPingAvgBean;
                    }
                });
        SingleOutputStreamOperator<HaoPingAvgRes> haoPingAvgResSingleOutputStreamOperator = reduceDS.flatMap(new FlatMapFunction<HaoPingAvgBean, HaoPingAvgRes>() {
            @Override
            public void flatMap(HaoPingAvgBean haoPingAvgBean, Collector<HaoPingAvgRes> collector) throws Exception {
                collector.collect(new HaoPingAvgRes(haoPingAvgBean.getSkuClass(), haoPingAvgBean.getPor_view() / haoPingAvgBean.getCount(), haoPingAvgBean.getTs()));
            }
        });
        haoPingAvgResSingleOutputStreamOperator.print("=======>");
        haoPingAvgResSingleOutputStreamOperator.addSink(MyClickHouseUtil.getSinkFunction("insert into  dws_haoping_avg_por_view values(?,?,?)"));
        env.execute("Dws_haoPing_avg_pro_view");
    }
}
